package com.nf.controller.home;

import com.google.gson.Gson;
import com.nf.controller.BaseServlet;
import com.nf.dao.UserInfoDao;
import com.nf.dao.impl.UserInfoDaoImpl;
import com.nf.util.GsonUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 编写servlet程序，实现用户修改密码
 */
@WebServlet("/api/UserUpdatePassServlet.do")
public class UserUpdatePassServlet extends BaseServlet {
    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedReader reader=req.getReader();
        String str=null;
        String jsonParams="";
        while ((str=reader.readLine())!=null){
            jsonParams=jsonParams+str;
        }
        Map<String,String> map= GsonUtil.parseMap(jsonParams);

        int id= Integer.parseInt(map.get("userId"));
        String rightPass=map.get("rightPass");
        String oldPass=map.get("oldPass");
        String newPass=map.get("newPass");


        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        // 判断用户输入的旧密码是否正确
        if(rightPass.equals(oldPass)){
            UserInfoDao dao=new UserInfoDaoImpl();
            int r=dao.updatePass(id,newPass);
            if(r==1){
                out.print(new Gson().toJson(successJson("修改成功")));
            }else {
                out.print(new Gson().toJson(errorJson("修改失败")));
            }

        }else {
            out.print(new Gson().toJson(errorJson("旧密码输入错误")));
        }
        out.flush();
        out.close();
    }
}
